<!--
  * 盘点单
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form" style="padding-left: 0" :model="from">
    <a-form-item label="" class="smart-query-form-item">
      <a-input v-model:value.trim="from.goods_name" placeholder="请输入商品名称进行查询" />
    </a-form-item>

    <!-- <a-form-item class="smart-query-form-item">
      <a-button-group>
        <a-button type="primary" html-type="submit" @click="onSearch" >
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="reset" >
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-button-group>
    </a-form-item> -->
  </a-form>
  <a-table :dataSource="tableDataComputed" :columns="columns" :pagination="false" rowKey="id" size="small" bordered :showExpandColumn="false" expandRowByClick>
    <template #bodyCell="{ text, record, column }">
      <template v-if="column.dataIndex === 'goods_name'">
        <CopyText :text="record.goods.goods_name">
          {{ record.goods.goods_name }}
        </CopyText>
      </template>
      <template v-if="column.dataIndex === 'img'">
        <a-image :width="30" :height="30" :src="record.goods.img" />
      </template>
      <template v-if="column.dataIndex === 'diff_num'">
        <span>{{ Number(text) < 0 ? '-' : '' }}{{ transformSpec(Math.abs(text), record.goods.spec) }}</span>
      </template>
      <template v-if="column.dataIndex === 'diff_price'">
        <span>{{ text }}</span>
      </template>
    </template>
    <template #expandedRowRender="{ record }">
      <div class="content">
        <div class="parent" v-for="item in record.batches" :key="item">
          <div class="div1">仓库：{{ item?.warehouse_code }}</div>
          <div class="div1">库位：{{ item?.location_code ? `${item.location_code}` : '' }}</div>
          <div class="div3">批次：{{ dayjs(item.batch_time).format('YYYY-MM-DD') }}</div>
          <div class="div2">原库存：{{ item.str_quantity }}</div>
          <div class="div2">现库存：{{ item.str_check_num }}</div>
          <a-button type="link" v-if="props.data.check_status == 1" @click="showModal(record, item)">编辑</a-button>
        </div>
      </div>
    </template>
  </a-table>
  <!-- <div class="smart-query-table-page">
    <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
  </div> -->
</template>
<script setup lang="ts">
import _ from 'lodash'
import dayjs from 'dayjs'
import { checkStockApi } from '@/api/business/storage/stocktaking-api'
import { message } from 'ant-design-vue'
import { useTransformSpec } from '@/hooks/web/use-transform-spec'
const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  }
})
const emit = defineEmits(['reload'])
const { transformSpec, openModal } = useTransformSpec()

const from = ref({
  goods_name: ''
})

// 表格
const columns = reactive([
  {
    title: '商品图片',
    dataIndex: 'img'
  },
  {
    title: '商品名称',
    dataIndex: 'goods_name'
  },
  {
    title: '商品编码',
    dataIndex: ['goods', 'no']
  },
  {
    title: '原库存',
    dataIndex: 'str_num'
  },
  {
    title: '现库存',
    dataIndex: 'str_check_num'
  },
  {
    title: '盈亏数量',
    dataIndex: 'diff_num'
  },
  {
    title: '盈亏金额',
    dataIndex: 'diff_price'
  }
])
const tableData = ref([])
const tableDataComputed = computed({
  get: () => {
    return tableData.value.filter((item) => {
      return item.goods.goods_name.includes(from.value.goods_name)
    })
  }
})
watch(
  () => props.data,
  (val) => {
    if (val) {
      tableData.value = val.detail.map((item: any) => {
        const batches = _.flatMapDeep(item.batches, (batche) => Object.values(batche)).map((batche) => {
          return {
            ...batche,
            str_quantity: transformSpec(batche.quantity, item.goods.spec),
            str_check_num: transformSpec(batche.check_num, item.goods.spec)
          }
        })
        return {
          ...item,
          batches,
          str_num: transformSpec(item.num, item.goods.spec),
          str_check_num: transformSpec(item.check_num, item.goods.spec),
          str_diff_num: transformSpec(item.diff_num, item.goods.spec)
        }
      })
      console.log(tableData.value)
    }
  },
  {
    deep: true,
    immediate: true
  }
)
// 修改数量
async function showModal(record, item) {
  // 打开弹窗
  openModal(item.check_num, record.goods.spec, record.goods.goods_name).then(async (quantity) => {
    try {
      const res = await updateNumber(quantity, { id: record.id, batches: item })
      await emit('reload', { id: props.data.id })
      message.success(res.msg)
    } catch (error) {
      message.error(error.msg)
    }
  })
}
async function updateNumber(number, { id, batches }) {
  const params = {
    id,
    batches: JSON.stringify([{ batch_id: batches.id, number }])
  }
  return await checkStockApi.modifyNum(params)
}
</script>
<style lang="less" scoped>
:deep(.ant-table-expanded-row .ant-table-cell) {
  background-color: #e6f4ff;
}
:deep(.ant-table-expanded-row .ant-table-cell:hover) {
  background-color: #e6f4ff;
}
.content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.parent {
  display: grid;
  grid-template-columns: 25% 20% 15% 10% 15% 15%;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  align-items: center;
}
.parent:last-of-type {
  border-bottom: none;
}
.div1 {
  font-weight: bold;
}
.div2 {
  display: flex;
  align-items: center;
  gap: 5px;
}
.div3 {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 显示省略符号来代表被修剪的文本 */
  width: 100%; /* 设置一个宽度限制，以便文本超出时能看到效果 */
}
</style>
